extends CharacterBody2D

# 配置参数
@export var max_speed = 200.0      # 最大冲刺速度
@export var acceleration_time = 1.5 # 加速到最大速度的时间（秒）
@export var rest_time = 1.0        # 冲刺后的休息时间（秒）

@onready var deathEffect = load("res://Effect/tscn/DeathEffect.tscn")
@onready var hurtEffect = load("res://Effect/tscn/HurtEffect.tscn")
@onready var money = load("res://Props/tscn/Money.tscn")
@onready var collision = $CollisionShape2D

# 状态变量
enum State {RESTING, CHARGING}
var current_state = State.RESTING
var target_position = Vector2.ZERO  # 冲刺目标位置
var charge_timer = 0.0                # 冲刺计时器
var rest_timer = 0.0                  # 休息计时器
var isWall = false
var charge_direction = Vector2.ZERO

# 节点引用
var player = null
@onready var eyes = $Eyes
@onready var wallActive = $WallActive
@onready var state = $State

func _ready():
	eyes.connect("body_entered", bodyEntered)
	eyes.connect("body_exited", bodyExited)
	wallActive.connect("body_entered", wallEnter)
	state.connect("death", death)
	state.connect("hurt", hurt)

func hurt(x):
	var effect = hurtEffect.instantiate()
	effect.global_position = global_position
	# 将动画效果放入世界节点
	get_tree().root.add_child(effect)

func death():
	# 效果节点
	var effect = deathEffect.instantiate()
	# 设置坐标, 绝对坐标
	effect.global_position = global_position
	# 将动画效果放入世界节点
	get_tree().root.add_child(effect)
	var moneyValue = RandomNumberGenerator.new().randi_range(20, 40)
	
	if moneyValue > 0:
		# 爆金币
		var obj = money.instantiate()
		obj.value = moneyValue
		obj.position = position
		self.get_parent().add_child(obj)
	queue_free()
	
func wallEnter(_wall):
	isWall = true
	
func bodyEntered(body):
	if body.name == "Player":
		player = body
	
	
func bodyExited(body):
	if body.name == "Player":
		player = null
	
	
func _physics_process(delta):
	match current_state:
		State.RESTING:
			rest_timer -= delta
			if rest_timer <= 0.0:
				start_charge()
		
		State.CHARGING:
			charge_timer += delta
			var t = charge_timer / acceleration_time
			
			# 使用锁定方向而非实时追踪
			velocity = charge_direction * lerp(0.0, max_speed, min(t, 1.0))
			move_and_slide()
			
			# 保持锁定方向的旋转
			#rotation = charge_direction.angle()
			
			if isWall:
				enter_rest()


func start_charge():
	if player:
		# 计算并锁定初始方向
		charge_direction = (player.global_position - global_position).normalized()
	else:
		charge_direction = Vector2.RIGHT  # 默认向右
		
	current_state = State.CHARGING
	charge_timer = 0.0
	isWall = false
	velocity = Vector2.ZERO


func enter_rest():
	current_state = State.RESTING
	rest_timer = rest_time
	velocity = Vector2.ZERO  # 停止移动
	charge_direction = Vector2.ZERO
